﻿module Sustainalytics.ProductInvolvement.Admin {

    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;

    export class PIBackendService {


        private $q: ng.IQService;
        private $http: ng.IHttpService;
        private notificationFactory: Common.INotificationFactory;
        private staticObjectsAdmin: CommonAdmin.IStaticObjects;
        private $location: ng.ILocationService;
        private $upload: any;
        private $filter: ng.IFilterProvider;

        constructor(
            $q: ng.IQService,
            $http: ng.IHttpService,
            notificationFactory: Common.INotificationFactory,
            staticObjectsAdmin: CommonAdmin.IStaticObjects,
            $location: ng.ILocationService,
            $upload,
            $filter: ng.IFilterProvider) {

            this.$q = $q;
            this.$http = $http;
            this.notificationFactory = notificationFactory;
            this.staticObjectsAdmin = staticObjectsAdmin;
            this.$upload = $upload;
            this.$location = $location;
            this.$filter = $filter;
        }

        public uploadPIInputFile(file: File, progress: number ): ng.IPromise<{}> {

            progress = 0;
            var ctx = this;
            var def = ctx.$q.defer();

            var reader = new FileReader();
            reader.onload = (data) => {
                return ctx.$upload.http({
                    method: "POST",
                    url: ctx.inputFileUrl(), 
                    headers: { 'Content-Disposition': 'attachment; filename="' + file.name + '"', 'Content-Type': file.type, },
                    data: reader.result
                })
                .progress(evt => { progress =  (100.0 * evt.loaded / evt.total); })                
                    .success((data) => { def.resolve(data); })
                    .error((data) => {def.resolve(data)});

            };
            reader.readAsArrayBuffer(file);
            return def.promise;
        }

        public cancelLastInputFile(id: string) {

            var ctx = this;     
            var def = this.$q.defer();
            var promise = ctx.$http({ method: "PATCH", url: ctx.inputFileUrl(), data: { Verb:"PATCH", ResourceId: id, Canceled:true} });
            promise
                .success(data => { def.resolve(data); })
                .error(err => { def.reject(err); });
            return def.promise;
        }

        public getLatestStatus(): ng.IHttpPromise<{}> {
            var ctx = this;

            return ctx.$http.get(ctx.inputFileUrl(), { params: { getLatest: true } });
        }

        public composeStatus(piinputfile: PIInputFileDto): string {
            var ctx = this;
            var result = 'No upload task scheduled';

            if (piinputfile && piinputfile.history.length > 1) {
                
                
                var lastEvent = piinputfile.history[piinputfile.history.length - 1].status;
                var createdDate = "";
                var startApplydDate = "";
                var failureDate = "";
                var successDate = "";

                var created = piinputfile.history.filter(x => x.status == PIUploadStatus.UploadValid);
                if (created && created.length >= 1)
                     createdDate = ctx.formatDateTime(created[0].dateTime);

                var startApply = piinputfile.history.filter(x => x.status == PIUploadStatus.AppliedStart);
                if (startApply && startApply.length >= 1)
                    startApplydDate = ctx.formatDateTime(startApply[0].dateTime);

                var failure = piinputfile.history.filter(x => x.status == PIUploadStatus.AppliedFailure);
                if (failure && failure.length >= 1)
                    failureDate = ctx.formatDateTime(failure[0].dateTime);

                var success = piinputfile.history.filter(x => x.status == PIUploadStatus.AppliedSuccess);
                if (success && success.length >= 1)
                    successDate = ctx.formatDateTime(success[0].dateTime);

                
                switch (lastEvent) {
                    case PIUploadStatus.None:                       result = 'No upload task scheduled'; break;                    
                    case PIUploadStatus.UploadValid :               result = 'One upload task scheduled for overnight publishing. File was uploaded on ' + createdDate; break;
                    case PIUploadStatus.AppliedSuccess:             result = 'One upload task created on ' + createdDate + ', that started on ' + startApplydDate + ' and completed successfully on ' + successDate + '.'; break;
                    case PIUploadStatus.AppliedFailure:             result = 'One upload task created on ' + createdDate + ', that started on ' + startApplydDate + ' and failed on ' + failureDate +'.'; break;
                    case PIUploadStatus.Canceled:                   result = 'No upload task scheduled'; break;
                }
            }
            return result;
        }

        private formatDateTime(adate: Date): string {
            var ctx = this;
            //    var fmt = ctx.$filter('date');

            //   return fmt(adate, 'dd/MM/yyyy HH:mm');

            return adate.toString();

        } 
        private inputFileUrl(): string {
            var ctx = this;
            return ctx.$location.protocol() + "://" + ctx.$location.host() + ":" + ctx.$location.port() +
                "/productinvolvementserv/api/v1/inputfile/";
        }
    }


    // register service with Tools Angular module
    var mod = angular.module(piAdminModuleName);

    mod.service('PIBackendService',
        ['$q', '$http', 'notificationFactory', 'staticObjectsAdmin', '$location', '$upload', '$filter', PIBackendService]);
}